package com.leapp.sk.ui.activity.login

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lkbasecomponent.util.LKDateTimeUtil
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import com.example.baselibrary.util.LKToastUtil
import com.example.mvp.activity.BaseActivityMVP
import com.example.mvp.binder.BaseDataBinder
import com.example.mvp.view.TimePicker.OnDateSetListener
import com.example.mvp.view.TimePicker.TimePickerDialog
import com.example.mvp.view.imgselector.ImageSelector
import com.example.util.FileSizeUtil
import com.example.util.MD5
import com.example.util.addYear
import com.leapp.sk.R
import com.leapp.sk.app.UPDATE_INFO
import com.leapp.sk.app.UP_FILE
import com.leapp.sk.bean.request.login.UPFileRequestEntity
import com.leapp.sk.bean.request.login.UpdatePersonalInfoRequestEntity
import com.leapp.sk.bean.response.login.UPFileResponseEntity
import com.leapp.sk.bean.response.login.UpdatePersonalInfoResponseEntity
import com.leapp.sk.binder.login.PerfectUserInfoBinder
import com.leapp.sk.inter.ImageHeadPathInterface
import com.leapp.sk.sever.login.PrefectUserInfoSever
import com.leapp.sk.ui.activity.join.SearchClassActivity
import com.leapp.sk.util.HeadImageCropUtil
import com.example.util.finallist.BABY_ID
import com.example.util.finallist.SKCODE_200
import com.leapp.sk.viewdelegate.login.PerfectUserInfoDelegate
import java.io.File
import java.io.IOException


/**
 * 完善用户信息
 * @author  chaohaipeng  on 2018/7/11.
 */
class PerfectUserInfoActivity : BaseActivityMVP<PerfectUserInfoDelegate>(), OnDateSetListener, ImageHeadPathInterface {
    /**
     * 时间选择器
     */
    private var mPickerDialog: TimePickerDialog? = null

    /**
     * 头像地址
     */
    private var headUrl: String = ""

    override fun initView(p0: Bundle?) {
        viewDelegate.setTitle(resources.getString(R.string.string_info_title))
        viewDelegate.initRelationshipDialog()
    }

    override fun initDate() {
        initSeleteDate()
    }

    override fun bindEvenListener() {
        viewDelegate.setOnClickListener(View.OnClickListener {
           viewDelegate.showRelationshipDialog()
        }, R.id.tv_apui_relationship)
        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.initSexDialog()
        }, R.id.tv_apui_sex)

        viewDelegate.setOnClickListener(View.OnClickListener {
            mPickerDialog?.show(fragmentManager, "info")
        }, R.id.tv_apui_birth_date)
        viewDelegate.setOnClickListener(View.OnClickListener {
            pickImage()
        }, R.id.iv_apui_head)

        viewDelegate.setOnClickListener(View.OnClickListener {
            if (!TextUtils.isEmpty(viewDelegate.nameCheck()) && !TextUtils.isEmpty(viewDelegate.sexCheck()) &&
                    !TextUtils.isEmpty(viewDelegate.birthCheck()) && !TextUtils.isEmpty(viewDelegate.relationCheck()) &&
                    !TextUtils.isEmpty(viewDelegate.myNameionCheck())) {
               httpUpdateData()
//                val intent: Intent = Intent(this@PerfectUserInfoActivity, SearchClassActivity::class.java)
//                intent.putExtra(BABY_ID,"")
//                startActivity(intent)
            }

        }, R.id.tv_apui_next)

    }

    override fun getDelegateClass(): Class<PerfectUserInfoDelegate> {
        return PerfectUserInfoDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return PerfectUserInfoBinder()
    }

    override fun onDateSet(timePickerView: TimePickerDialog?, millseconds: Long) {
        val timeData = LKDateTimeUtil.formatDateTime(millseconds, "yyyy-MM-dd")
        viewDelegate.setTimeData(timeData)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        HeadImageCropUtil.getResultHeadFile(requestCode, resultCode, data, this, this)
    }


    /**
     * 头像选择
     */
    private fun pickImage() {
        ImageSelector.getInstance()
                .setSelectModel(ImageSelector.MULTI_MODE)
                .setMaxCount(1)
                .setGridColumns(3)
                .setShowCamera(true)
                .startSelect(this)
    }

    /**
     * 初始化时间选择器
     */
    private fun initSeleteDate() {
        var tenYears = addYear(-5)
        var endYears = addYear(5)
        mPickerDialog = TimePickerDialog.Builder()
                .setCallBack(this)
                .setCyclic(false)
                .setMinMillseconds(tenYears)
                .setThemeColor(ContextCompat.getColor(this, R.color.color_E0E0E0))
                .setTitleStringId(resources.getString(R.string.string_time_chose_title))
                .setWheelItemTextNormalColor(ContextCompat.getColor(this, R.color.color_A3A5A8))
                .setWheelItemTextSelectorColor(ContextCompat.getColor(this, R.color.color_474747))
                .setWheelItemTextSize(15)
                .setMaxMillseconds(endYears)
                .setVisiblesYMD(true)
                .setCurrentMillseconds(System.currentTimeMillis())
                .build()
    }

    override fun getImageHeadFile(file: File?) {
        httpUpFile(file)
    }

    /**
     * 更新数据
     */
    private fun httpUpdateData() {
        val updatePersonalInfoRequestEntity = UpdatePersonalInfoRequestEntity()
        updatePersonalInfoRequestEntity.parentId=updatePersonalInfoRequestEntity.userId
        updatePersonalInfoRequestEntity.avatar =headUrl
        updatePersonalInfoRequestEntity.birthday=viewDelegate.birthCheck()
        updatePersonalInfoRequestEntity.childName=viewDelegate.nameCheck()
        updatePersonalInfoRequestEntity.parentName=viewDelegate.nameCheck()
        updatePersonalInfoRequestEntity.sex=viewDelegate.getsex()
        updatePersonalInfoRequestEntity.relative=viewDelegate.relationCheck()
                LKHttp.post(UPDATE_INFO, updatePersonalInfoRequestEntity, UpdatePersonalInfoResponseEntity::class.java, object : BaseCallBack<UpdatePersonalInfoResponseEntity>(this) {
                    override fun onSuccess(url: String?, resultText: String?, obj: UpdatePersonalInfoResponseEntity?) {
                        super.onSuccess(url, resultText, obj)
                        if (obj?.code == SKCODE_200) {
                            val intent: Intent = Intent(this@PerfectUserInfoActivity, SearchClassActivity::class.java)
                            intent.putExtra(BABY_ID,obj?.data)
                            startActivity(intent)
                        } else {
                            LKToastUtil.showToastShort(obj?.message)
                        }
                    }

                    override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                        super.onFailure(url, isLoading, exceptionStr)
                        LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
                    }
                }
                        , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

    /**
     * 上传文件
     */
    private fun httpUpFile(file: File?) {
        if (file == null) {
            return
        }
        val upFileRequestEntity = UPFileRequestEntity()
        upFileRequestEntity.appKey = "leapp_sk"
        upFileRequestEntity.ext = FileSizeUtil.getInstance().getFileHname(file.absolutePath)
        upFileRequestEntity.file = file
        try {
            upFileRequestEntity.md5 = (MD5.md5(file))
        } catch (e: IOException) {
            e.printStackTrace()
        }
        upFileRequestEntity.fileSize = FileSizeUtil.getInstance().getFileOrFilesIntSize(file.absolutePath, FileSizeUtil.SIZETYPE_KB)
        LKHttp.upLoad(UP_FILE, upFileRequestEntity, UPFileResponseEntity::class.java, object : BaseCallBack<UPFileResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: UPFileResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.statusCode == SKCODE_200) {
                    val url1 = PrefectUserInfoSever.getInstance().getUrl(obj)
                    viewDelegate.setHeadData(url1)
                } else {
                    LKToastUtil.showToastShort(obj?.statusMessage)
                }
            }

            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

}